/**
 * Memory transport implementation for XDevice
 * 用于进程内通信的内存传输层
 */

#include <xdevice/transport.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

/* 内存传输结构 */
typedef struct {
    pthread_mutex_t lock;
    char* buffer;
    size_t buffer_size;
    size_t data_size;
    bool initialized;
} memory_transport_t;

static memory_transport_t g_memory_transport = {0};

int xdevice_transport_memory_init(size_t buffer_size) {
    if (g_memory_transport.initialized) {
        return 0; // Already initialized
    }
    
    if (pthread_mutex_init(&g_memory_transport.lock, NULL) != 0) {
        return -1;
    }
    
    g_memory_transport.buffer = malloc(buffer_size);
    if (!g_memory_transport.buffer) {
        pthread_mutex_destroy(&g_memory_transport.lock);
        return -1;
    }
    
    g_memory_transport.buffer_size = buffer_size;
    g_memory_transport.data_size = 0;
    g_memory_transport.initialized = true;
    
    return 0;
}

void xdevice_transport_memory_cleanup(void) {
    if (!g_memory_transport.initialized) {
        return;
    }
    
    pthread_mutex_lock(&g_memory_transport.lock);
    
    if (g_memory_transport.buffer) {
        free(g_memory_transport.buffer);
        g_memory_transport.buffer = NULL;
    }
    
    g_memory_transport.buffer_size = 0;
    g_memory_transport.data_size = 0;
    g_memory_transport.initialized = false;
    
    pthread_mutex_unlock(&g_memory_transport.lock);
    pthread_mutex_destroy(&g_memory_transport.lock);
}

int xdevice_transport_memory_send(const void* data, size_t size) {
    if (!g_memory_transport.initialized || !data || size == 0) {
        return -1;
    }
    
    pthread_mutex_lock(&g_memory_transport.lock);
    
    if (size > g_memory_transport.buffer_size) {
        pthread_mutex_unlock(&g_memory_transport.lock);
        return -1; // Data too large
    }
    
    memcpy(g_memory_transport.buffer, data, size);
    g_memory_transport.data_size = size;
    
    pthread_mutex_unlock(&g_memory_transport.lock);
    return size;
}

int xdevice_transport_memory_recv(void* buffer, size_t buffer_size) {
    if (!g_memory_transport.initialized || !buffer || buffer_size == 0) {
        return -1;
    }
    
    pthread_mutex_lock(&g_memory_transport.lock);
    
    size_t copy_size = (g_memory_transport.data_size < buffer_size) ? 
                       g_memory_transport.data_size : buffer_size;
    
    if (copy_size > 0) {
        memcpy(buffer, g_memory_transport.buffer, copy_size);
    }
    
    pthread_mutex_unlock(&g_memory_transport.lock);
    return copy_size;
}
